package com.qiangesoft.blog.file.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qiangesoft.blog.file.config.FileStoreConfig;
import com.qiangesoft.blog.file.enums.FileStoreTypeEnum;
import com.qiangesoft.blog.file.enums.FileTypeEnum;
import com.qiangesoft.blog.file.entity.SysFileInfo;
import com.qiangesoft.blog.file.core.minio.MinioTemplate;
import com.qiangesoft.blog.file.service.ISysFileInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 文件清理定时任务
 *
 * @author qiange
 * @date 2023-04-28
 */
@Component
public class ClearExpireFileScheduled {

    @Autowired
    private ISysFileInfoService fileInfoService;
    @Autowired
    private MinioTemplate minioTemplate;
    @Autowired
    private FileStoreConfig fileStoreConfig;

    /**
     * 每日凌晨2点执行
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void timerTask() {
        long expires = fileStoreConfig.getMinioConfig().getExpires();
        LambdaQueryWrapper<SysFileInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysFileInfo::getExpireFlag, false)
                .eq(SysFileInfo::getStoreType, FileStoreTypeEnum.FILE_MINIO.getCode())
                .eq(SysFileInfo::getCategory, FileTypeEnum.IMAGE.getCode())
                .le(SysFileInfo::getCreateTime, LocalDateTime.now().minusSeconds(expires / 1000));
        List<SysFileInfo> sysFileInfoList = fileInfoService.list(queryWrapper);

        // 删除图片
        Map<String, List<SysFileInfo>> map = sysFileInfoList.stream().collect(Collectors.groupingBy(SysFileInfo::getCategory));
        for (Map.Entry<String, List<SysFileInfo>> files : map.entrySet()) {
            List<SysFileInfo> infoList = files.getValue();
            List<String> objectNames = infoList.stream().map(SysFileInfo::getFileName).collect(Collectors.toList());
            try {
                minioTemplate.removeObjects(objectNames);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        if (CollectionUtils.isEmpty(sysFileInfoList)) {
            return;
        }

        // 置为失效
        List<Long> fileIds = sysFileInfoList.stream().map(SysFileInfo::getId).collect(Collectors.toList());
        LambdaUpdateWrapper<SysFileInfo> updateQuery = new LambdaUpdateWrapper<>();
        updateQuery.in(SysFileInfo::getId, fileIds)
                .set(SysFileInfo::getExpireFlag, true);
        fileInfoService.update(updateQuery);
    }
}
